/**
 * @author 太阳当空丶赵
 * @date 2022/12/1-16:54
 * @version 1.0.0
 * admin
 */
const express = require("express")
const expressJoi = require("@escook/express-joi")
const jsonwebtoken = require("jsonwebtoken")

const BaseResult = require("../utils/result/BaseResult")
const {adminLoginRules} = require("../utils/rules/adminLoginRules")
const {getFeedbackListRules} = require('../utils/rules/getFeedbackListRules')
const {secretKey} = require("../config")

const {
    selectAll,
    selectFeedbackListByPage,
} = require("../database/mapper")

const adminRouter = express.Router()

// 管理员身份判断
adminRouter.all("*", (req, res, nest) => {
    const {path} = req
    if (path === "/login") return nest()
    const {userRole} = req.auth
    if (userRole) return nest()
    res.send(BaseResult.userValidateFailed())
})

/**
 * 管理员登录
 * */
adminRouter.post("/login", expressJoi(adminLoginRules), async (req, res) => {
    const {username, password} = req.body
    const result = (await selectAll("user", {username}))[0]
    if (!result || result.password !== password) return res.send(BaseResult.userValidateFailed())
    const adminData = {
        userId: result['user_id'],
        userRole: result['user_role']
    }
    const token = jsonwebtoken.sign(
        adminData, secretKey, {expiresIn: "360000s"/*有效时间*/})
    return res.send(BaseResult.success(token))
})

/**
 * 获取用户提交的反馈信息
 * 根据时间进行排序
 * */
adminRouter.post("/getFeedbackListByPage", expressJoi(getFeedbackListRules), async (req, res) => {
    const {pageNum, pageSize, beforeDate, afterDate} = req.body
    console.log(beforeDate, afterDate)
    try {
        const result = await selectFeedbackListByPage({
            before: (pageNum - 1) * pageSize,
            after: pageNum * pageSize,
            beforeDate,
            afterDate
        })
        res.send(BaseResult.success(result))
    } catch (e) {
        return res.send(BaseResult.error())
    }
})


module.exports = adminRouter
